package cn.moonspace.flowerowner.controller;

import java.io.IOException;

import javax.validation.Valid;

import net.sf.json.JSONObject;

import org.apache.http.client.ClientProtocolException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xml.sax.SAXException;

import cn.moonspace.flowerowner.exception.DriverException;
import cn.moonspace.flowerowner.form.DriverForm;
import cn.moonspace.flowerowner.form.RegulationForm;

/**
 * 查违章功能
 * 
 * @author diyongchao
 *
 */
@Controller
public class SearchReglController extends BaseController {

	@RequestMapping(value="/search/regulations", method=RequestMethod.GET) 
	public String prepSearchRegulations(ModelMap modelMap) {
		modelMap.addAttribute("regulationForm", new RegulationForm());
		modelMap.addAttribute(PAGE_PATH, "searchRegulations");
		return LAYOUT_PAGE;
	}
	
	/**
	 * 查违章POST处理
	 * 
	 * @param regulationForm
	 * @return
	 * @throws DriverException 
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws SAXException
	 */
	@RequestMapping(value="/search/regulations", method=RequestMethod.POST) 
	public @ResponseBody Object postSearchRegulations(
			@Valid @ModelAttribute("regulationForm") RegulationForm regulationForm, Errors errors) throws DriverException  {
		if(errors.hasErrors()) {
			JSONObject result = new JSONObject();
			result.put("error", errors.getFieldErrors().get(0).getDefaultMessage());
			return result;
		} else {
			return regulationService.searchRegulation(regulationForm); 
		}
	}
	
	@RequestMapping(value="/search/driver", method=RequestMethod.POST) 
	public @ResponseBody Object postSearchDriver(
			@Valid @ModelAttribute("driverForm") DriverForm driverForm, Errors errors) throws DriverException  {
		if(errors.hasErrors()) {
			JSONObject result = new JSONObject();
			result.put("error", errors.getFieldErrors().get(0).getDefaultMessage());
			return result;
		} else {
			return regulationService.searchDriver(driverForm); 
		}
	}
	
}
